package com.rigi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rigi.common.R;
import com.rigi.entity.User;
import com.rigi.service.UserService;
import com.rigi.utils.SMSUtils;
import com.rigi.utils.ValidateCodeUtils;
import io.lettuce.core.GeoArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.el.util.Validation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String checkCode = ValidateCodeUtils.generateValidateCode(4).toString();

        if (user.getPhone() != null) {
//            SMSUtils.sendMessage("瑞吉外卖","",phone,checkCode);
//            session.setAttribute(user.getPhone(), checkCode);
            //使用redis缓存短信验证码
            redisTemplate.opsForValue().set(user.getPhone(),checkCode,1, TimeUnit.MINUTES);
            log.info("验证码：" + checkCode);
            return R.success("发送验证码成功");
        }
        return R.error("发送验证码失败");


    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        String phone = (String) map.get("phone");
//        String checkCode = (String) session.getAttribute(phone);

        //从redis中获取短信验证码
        String checkCode = (String)redisTemplate.opsForValue().get(phone);

        if (checkCode.equals(map.get("code"))) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("phone", phone);

            User user = userService.getOne(userQueryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user);
            //用户登录成功删除redis中的短信验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误");
    }
}
